import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../core/app_initializer.dart';

class AppPrefsManager {
  AppPrefsManager._();

  static SharedPreferences get instance => AppInitializer.prefs;

  /// 泛型存储
  static Future<void> set<T>(String key, T value) async {
    if (T == String) {
      await instance.setString(key, value as String);
    } else if (T == int) {
      await instance.setInt(key, value as int);
    } else if (T == double) {
      await instance.setDouble(key, value as double);
    } else if (T == bool) {
      await instance.setBool(key, value as bool);
    } else if (T == List<String>) {
      await instance.setStringList(key, value as List<String>);
    } else if (T == Map<String, dynamic>) {
      final jsonString = jsonEncode(value);
      await instance.setString(key, jsonString);
    } else if (T == List<Map<String, dynamic>>) {
      final jsonString = jsonEncode(value);
      await instance.setString(key, jsonString);
    } else {
      throw UnsupportedError("Type $T is not supported");
    }
  }

  /// 泛型读取
  static T? get<T>(String key) {
    final value = instance.get(key);
    if (value == null) return null;

    if (T == String) return value as T;
    if (T == int) return value as T;
    if (T == double) return value as T;
    if (T == bool) return value as T;
    if (T == List<String>) return (value as List).cast<String>() as T;
    if (T == Map<String, dynamic>) {
      if (value is String) {
        return jsonDecode(value) as T;
      }
    }
    if (T == List<Map<String, dynamic>>) {
      if (value is String) {
        final decoded = jsonDecode(value) as List;
        return decoded.map((e) => Map<String, dynamic>.from(e)).toList() as T;
      }
    }

    throw UnsupportedError("Type $T is not supported");
  }

  /// 删除
  static Future<void> remove(String key) async {
    await instance.remove(key);
  }

  /// 清空
  static Future<void> clear() async {
    await instance.clear();
  }
}
